package org.lilred.nzbberry.views;

import org.lilred.nzbberry.Themes;
import org.lilred.ui.theme.Theme;
import org.lilred.ui.theme.Themeable;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.ScrollChangeListener;

public class PageView extends Manager implements ScrollChangeListener, Themeable {
	int padding;
	private Theme defaultTheme = Themes.CONTENT.clone();
	
	public PageView(int padding) {
		super(VERTICAL_SCROLL | USE_ALL_HEIGHT);
		this.padding = padding;
		setScrollListener(this);
	}
	
	public PageView() {
		super(VERTICAL_SCROLL | USE_ALL_HEIGHT);
		setScrollListener(this);
	}
	
	public PageView(long style) {
		super(style);
		setScrollListener(this);
	}
	
	protected void paint(Graphics g) {
		getDefaultTheme().paint(getWidth(), getHeight(), g);
		super.paint(g);
		int verticalScroll = getVerticalScroll();
		int visibleHeight = getVisibleHeight();
		int virtualHeight = getVirtualHeight();
		if (verticalScroll + visibleHeight < virtualHeight) {
			Bitmap scrollDown = Bitmap.getBitmapResource("scroll-down.png");
			g.drawBitmap(getWidth() - scrollDown.getWidth(), verticalScroll + visibleHeight - scrollDown.getHeight(), scrollDown.getWidth(), scrollDown.getHeight(), scrollDown, 0, 0);
		}
		if (verticalScroll != 0) {
			Bitmap scrollUp = Bitmap.getBitmapResource("scroll-up.png");
			g.drawBitmap(getWidth() - scrollUp.getWidth(), verticalScroll, scrollUp.getWidth(), scrollUp.getHeight(), scrollUp, 0, 0);
		}
	}
	
	protected void sublayout(int width, int height) {
		int offset = padding;
		for (int i = 0; i < getFieldCount(); i++) {
			layoutChild(getField(i), width - 2 * padding, height);
			if ((getField(i).getStyle() & Field.FIELD_HCENTER) == Field.FIELD_HCENTER) 
				setPositionChild(getField(i), width/2 - getField(i).getWidth()/2, offset);
			else if ((getField(i).getStyle() & Field.FIELD_RIGHT) == Field.FIELD_RIGHT)
				setPositionChild(getField(i), width - padding - getField(i).getWidth(), offset);
			else setPositionChild(getField(i), padding, offset);
			offset += getField(i).getHeight() + padding;
		}
		offset += padding;
		setExtent(width, height);
		setVirtualExtent(width, offset);
	}

	public void scrollChanged(Manager manager, int newHorizontalScroll, int newVerticalScroll) {
		invalidate();
	}

	public Theme getActiveTheme() {
		return null;
	}

	public Theme getDefaultTheme() {
		return defaultTheme;
	}

	public Theme getFocusTheme() {
		return null;
	}
}
